import React, { useState } from 'react';
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  DatePicker,
  Select,
  Tag,
  Space,
  Typography,
  Row,
  Col,
  message,
  Timeline,
  Rate,
  Progress,
  List,
  Avatar,
} from 'antd';
import {
  PlusOutlined,
  PlayCircleOutlined,
  CalendarOutlined,
  TeamOutlined,
  CustomerServiceOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';

const { Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;

const Rehearsals = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingRehearsal, setEditingRehearsal] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');

  // 模拟数据
  const [rehearsals, setRehearsals] = useState([
    {
      key: '1',
      date: '2024-01-18',
      time: '14:00-16:00',
      location: '排练室A',
      participants: ['张三', '李四', '王五', '赵六'],
      songs: ['夜空中最亮的星', '海阔天空'],
      duration: '2小时',
      status: 'completed',
      overallRating: 4,
      notes: '整体表现良好，海阔天空的副歌部分需要加强练习',
      attendance: 4,
      totalMembers: 5,
    },
    {
      key: '2',
      date: '2024-01-15',
      time: '19:00-21:00',
      location: '排练室B',
      participants: ['张三', '李四', '王五', '赵六', '钱七'],
      songs: ['光辉岁月', '童话'],
      duration: '2小时',
      status: 'completed',
      overallRating: 5,
      notes: '非常棒的排练，所有歌曲都表现得很出色',
      attendance: 5,
      totalMembers: 5,
    },
    {
      key: '3',
      date: '2024-01-12',
      time: '15:00-17:00',
      location: '排练室A',
      participants: ['张三', '李四', '王五'],
      songs: ['夜空中最亮的星'],
      duration: '2小时',
      status: 'completed',
      overallRating: 3,
      notes: '主歌部分需要改进，节奏感有待提升',
      attendance: 3,
      totalMembers: 5,
    },
    {
      key: '4',
      date: '2024-01-20',
      time: '14:00-16:00',
      location: '排练室A',
      participants: ['张三', '李四', '王五', '赵六', '钱七'],
      songs: ['夜空中最亮的星', '海阔天空', '光辉岁月'],
      duration: '2小时',
      status: 'upcoming',
      overallRating: null,
      notes: '',
      attendance: 0,
      totalMembers: 5,
    },
  ]);

  const songOptions = [
    { value: '夜空中最亮的星', label: '夜空中最亮的星' },
    { value: '海阔天空', label: '海阔天空' },
    { value: '光辉岁月', label: '光辉岁月' },
    { value: '童话', label: '童话' },
    { value: '小幸运', label: '小幸运' },
    { value: '演员', label: '演员' },
  ];

  const memberOptions = [
    { value: '张三', label: '张三 (主唱)' },
    { value: '李四', label: '李四 (吉他)' },
    { value: '王五', label: '王五 (贝斯)' },
    { value: '赵六', label: '赵六 (鼓手)' },
    { value: '钱七', label: '钱七 (键盘)' },
  ];

  const columns = [
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
      render: (date, record) => (
        <div>
          <div>{date}</div>
          <div style={{ fontSize: 12, color: '#666' }}>{record.time}</div>
        </div>
      ),
    },
    {
      title: '地点',
      dataIndex: 'location',
      key: 'location',
    },
    {
      title: '参与人数',
      key: 'attendance',
      render: (_, record) => (
        <div>
          <div>{record.attendance}/{record.totalMembers}</div>
          <Progress 
            percent={Math.round((record.attendance / record.totalMembers) * 100)} 
            size="small" 
            showInfo={false}
          />
        </div>
      ),
    },
    {
      title: '练习歌曲',
      dataIndex: 'songs',
      key: 'songs',
      render: (songs) => (
        <div>
          {songs.map(song => (
            <Tag key={song} color="blue" style={{ marginBottom: 4 }}>
              {song}
            </Tag>
          ))}
        </div>
      ),
    },
    {
      title: '时长',
      dataIndex: 'duration',
      key: 'duration',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          completed: { color: 'green', text: '已完成', icon: <CheckCircleOutlined /> },
          upcoming: { color: 'blue', text: '即将开始', icon: <ClockCircleOutlined /> },
          cancelled: { color: 'red', text: '已取消', icon: <DeleteOutlined /> },
        };
        const config = statusMap[status] || { color: 'default', text: '未知', icon: null };
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: '整体评分',
      dataIndex: 'overallRating',
      key: 'overallRating',
      render: (rating) => rating ? <Rate disabled defaultValue={rating} /> : '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            详情
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleView = (record) => {
    Modal.info({
      title: `排练记录 - ${record.date}`,
      width: 700,
      content: (
        <div>
          <Row gutter={[16, 16]}>
            <Col span={12}>
              <Card title="基本信息" size="small">
                <p><strong>日期：</strong> {record.date}</p>
                <p><strong>时间：</strong> {record.time}</p>
                <p><strong>地点：</strong> {record.location}</p>
                <p><strong>时长：</strong> {record.duration}</p>
                <p><strong>状态：</strong> 
                  {(() => {
                    const statusMap = {
                      completed: { color: 'green', text: '已完成' },
                      upcoming: { color: 'blue', text: '即将开始' },
                      cancelled: { color: 'red', text: '已取消' },
                    };
                    const config = statusMap[record.status];
                    return <Tag color={config.color}>{config.text}</Tag>;
                  })()}
                </p>
              </Card>
            </Col>
            <Col span={12}>
              <Card title="参与成员" size="small">
                <List
                  size="small"
                  dataSource={record.participants}
                  renderItem={(member) => (
                    <List.Item>
                      <List.Item.Meta
                        avatar={<Avatar icon={<TeamOutlined />} />}
                        title={member}
                      />
                    </List.Item>
                  )}
                />
              </Card>
            </Col>
          </Row>
          <Card title="练习歌曲" size="small" style={{ marginTop: 16 }}>
            <Timeline>
              {record.songs.map((song, index) => (
                <Timeline.Item key={index}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <CustomerServiceOutlined />
                    <span>{song}</span>
                    <Tag color="blue">第{index + 1}首</Tag>
                  </div>
                </Timeline.Item>
              ))}
            </Timeline>
          </Card>
          {record.overallRating && (
            <Card title="整体评分" size="small" style={{ marginTop: 16 }}>
              <Rate disabled defaultValue={record.overallRating} />
              <div style={{ marginTop: 8 }}>
                <strong>评分：</strong> {record.overallRating}/5
              </div>
            </Card>
          )}
          {record.notes && (
            <Card title="排练备注" size="small" style={{ marginTop: 16 }}>
              <p>{record.notes}</p>
            </Card>
          )}
        </div>
      ),
    });
  };

  const handleEdit = (record) => {
    setEditingRehearsal(record);
    setIsModalVisible(true);
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除排练记录 "${record.date}" 吗？`,
      onOk() {
        setRehearsals(rehearsals.filter(item => item.key !== record.key));
        message.success('删除成功');
      },
    });
  };

  const handleAdd = () => {
    setEditingRehearsal(null);
    setIsModalVisible(true);
  };

  const handleModalOk = () => {
    setIsModalVisible(false);
    setEditingRehearsal(null);
    message.success(editingRehearsal ? '更新成功' : '添加成功');
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
    setEditingRehearsal(null);
  };

  const filteredRehearsals = rehearsals.filter(item => {
    const matchesSearch = item.location.toLowerCase().includes(searchText.toLowerCase()) ||
                         item.songs.some(song => song.toLowerCase().includes(searchText.toLowerCase()));
    const matchesStatus = filterStatus === 'all' || item.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  return (
    <div>
      <Title level={2}>排练记录</Title>

      {/* 搜索和过滤 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col xs={24} sm={12} md={8}>
            <Input
              placeholder="搜索地点或歌曲"
              allowClear
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              prefix={<PlayCircleOutlined />}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <Select
              placeholder="选择状态"
              style={{ width: '100%' }}
              value={filterStatus}
              onChange={setFilterStatus}
            >
              <Option value="all">全部状态</Option>
              <Option value="completed">已完成</Option>
              <Option value="upcoming">即将开始</Option>
              <Option value="cancelled">已取消</Option>
            </Select>
          </Col>
          <Col xs={24} sm={24} md={10}>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                添加排练
              </Button>
              <Button icon={<CalendarOutlined />}>
                导出记录
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 统计信息 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={8}>
          <Card size="small">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 24, fontWeight: 'bold', color: '#1890ff' }}>
                {rehearsals.length}
              </div>
              <div>总排练次数</div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card size="small">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 24, fontWeight: 'bold', color: '#52c41a' }}>
                {rehearsals.filter(r => r.status === 'completed').length}
              </div>
              <div>已完成</div>
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card size="small">
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 24, fontWeight: 'bold', color: '#faad14' }}>
                {Math.round(rehearsals.reduce((sum, r) => sum + (r.overallRating || 0), 0) / 
                           rehearsals.filter(r => r.overallRating).length)}
              </div>
              <div>平均评分</div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 排练记录列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={filteredRehearsals}
          pagination={{
            total: filteredRehearsals.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 添加/编辑排练模态框 */}
      <Modal
        title={editingRehearsal ? '编辑排练' : '添加排练'}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        width={700}
      >
        <Form
          layout="vertical"
          initialValues={editingRehearsal || {}}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="排练日期"
                name="date"
                rules={[{ required: true, message: '请选择排练日期' }]}
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="排练时间"
                name="time"
                rules={[{ required: true, message: '请输入排练时间' }]}
              >
                <Input placeholder="例如: 14:00-16:00" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="排练地点"
                name="location"
                rules={[{ required: true, message: '请输入排练地点' }]}
              >
                <Input placeholder="请输入排练地点" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="排练状态"
                name="status"
                rules={[{ required: true, message: '请选择排练状态' }]}
              >
                <Select placeholder="请选择排练状态">
                  <Option value="upcoming">即将开始</Option>
                  <Option value="completed">已完成</Option>
                  <Option value="cancelled">已取消</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            label="参与成员"
            name="participants"
            rules={[{ required: true, message: '请选择参与成员' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择参与成员"
              options={memberOptions}
            />
          </Form.Item>
          <Form.Item
            label="练习歌曲"
            name="songs"
            rules={[{ required: true, message: '请选择练习歌曲' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择练习歌曲"
              options={songOptions}
            />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="整体评分"
                name="overallRating"
              >
                <Select placeholder="请选择评分">
                  <Option value={1}>1星</Option>
                  <Option value={2}>2星</Option>
                  <Option value={3}>3星</Option>
                  <Option value={4}>4星</Option>
                  <Option value={5}>5星</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="排练时长"
                name="duration"
                rules={[{ required: true, message: '请输入排练时长' }]}
              >
                <Input placeholder="例如: 2小时" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            label="排练备注"
            name="notes"
          >
            <TextArea rows={4} placeholder="请输入排练备注" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Rehearsals; 